<script setup lang="ts">
/**
 * @用途
 * @author bear
 * @创建时间 2025/11/19
 **/
import { mdiBookmarkMultiple, mdiFolderOutline, mdiStar, mdiStarOutline } from '@mdi/js'
import { useI18n } from 'vue-i18n'
import { useBookmarkManagerStore } from '@/stores/bookmarkManager'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'

const layoutStore = useLayoutStore()
const bookmarkManagerStore = useBookmarkManagerStore()
const prop = defineProps<{ tab: F2.tab.Entity }>()
// 显隐状态：手动控制，避免因父级输入框行为导致默认点击未生效
const showPop = computed({
  get() {
    return layoutStore.showBookmarkIds.has(prop.tab.id)
  },
  set(value) {
    if (value) {
      layoutStore.showBookmarkIds.add(prop.tab.id)
    } else {
      layoutStore.showBookmarkIds.delete(prop.tab.id)
    }
  }
})
const canAddBookmark = computed(() => {
  return prop.tab.url.startsWith('http')
})
const currentBookmark = computed(() => {
  return bookmarkManagerStore.items.find(item => item.link === prop.tab.url)
})
const isBookmarked = computed(() => {
  return Boolean(currentBookmark.value)
})
// i18n
const { t } = useI18n()

let bookmark = reactive<F2.bookmark.BookmarkLocal>({
  _id: '',
  link: prop.tab.url,
  title: prop.tab.title,
  favicon: prop.tab.favicon
})

// 切换书签状态
async function addBookmark() {
  if (!canAddBookmark.value) return
  const b = JSON.parse(JSON.stringify(bookmark))

  if (bookmark._id) {
    await bookmarkManagerStore.updateBookmark(b)
  } else {
    await bookmarkManagerStore.addBookmark(b)
  }
  if (currentBookmark.value) bookmark._id = currentBookmark.value._id
}

async function removeBookmark() {
  if (!currentBookmark.value) return
  await bookmarkManagerStore.deleteBookmark(currentBookmark.value._id)
  showPop.value = false
}

onMounted(async () => {
  await bookmarkManagerStore.loadBookmarks()
  if (currentBookmark.value) Object.assign(bookmark, currentBookmark.value)
})
watch(showPop, v => {
  bookmark = {
    _id: currentBookmark.value?._id || '',
    link: prop.tab.url,
    title: prop.tab.title,
    favicon: prop.tab.favicon
  }
  if (v && !bookmark._id) addBookmark()
})

watch(
  () => prop.tab.favicon,
  (v, ov) => {
    if (v && v !== ov && currentBookmark.value) {
      Object.assign(bookmark, { ...currentBookmark.value, favicon: v })
      addBookmark()
    }
  },
  { immediate: true }
)
</script>

<template>
  <v-menu
    v-if="canAddBookmark"
    v-model="showPop"
    :close-on-content-click="false"
    location="bottom"
    :offset="6"
  >
    <template #activator="{ props }">
      <v-btn
        v-bind="props"
        class="cursor-pointer"
        :color="isBookmarked ? 'primary' : ''"
        data-testid="webContent-bookmark-toggle"
        density="compact"
        :icon="isBookmarked ? mdiStar : mdiStarOutline"
        :title="isBookmarked ? t('bookmark.remove') : t('bookmark.add')"
        @mousedown.stop
      />
    </template>

    <v-card
      class="bookmark-pop pa-2"
      elevation="16"
      :subtitle="bookmark.link"
      :title="t('bookmark.added') + ' - ' + bookmark.title"
    >
      <template #prepend>
        <v-avatar :image="bookmark.favicon" size="32" />
      </template>
      <v-card-text>
        <v-text-field
          v-model="bookmark.title"
          density="compact"
          :prepend-icon="mdiBookmarkMultiple"
        >
        </v-text-field>
        <v-select
          v-model="bookmark.folder_id"
          item-title="name"
          item-value="_id"
          :items="bookmarkManagerStore.folders"
          :label="t('bookmark.selectFolder')"
          :prepend-icon="mdiFolderOutline"
          @update:model-value="addBookmark"
        />
      </v-card-text>
      <v-card-actions class="justify-end">
        <v-btn color="primary" variant="flat" @click="showPop = false">
          {{ t('bookmark.done') }}
        </v-btn>
        <v-btn v-if="isBookmarked" variant="tonal" @click="removeBookmark">
          {{ t('bookmark.remove') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-menu>
</template>

<style scoped>
.bookmark-pop {
  min-width: 320px;
  max-width: 420px;
}
</style>
<i18n>
{
  "zhHans": {
    "bookmark": {
      "add": "添加",
      "remove": "移除",
      "added": "已添加",
      "title": "标题",
      "folder": "文件夹",
      "done": "完成",
      "unfiled": "未分类",
      "selectFolder": "选择文件夹"
    }
  },
  "en": {
    "bookmark": {
      "add": "Add",
      "remove": "Remove",
      "added": "Added",
      "title": "Title",
      "folder": "Folder",
      "done": "Done",
      "unfiled": "Unfiled",
      "selectFolder": "Select Folder"
    }
  }
}
</i18n>
